package controller;

import java.io.IOException;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import bean.BookBean;

public class ShoppingCart extends HttpServlet
{
	HttpSession session;
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		session = request.getSession(true);		
		Integer bookId = Integer.parseInt(request.getParameter("bookId"));
		
		try 
		{
			String address = "";
			if (IsCustomerLoggedIn()) 
			{
				BookBean selectedBook = GetSelectedBook(bookId);
				AddToCart(selectedBook);
				address = "/WEB-INF/checkout.jsp";
				session.setAttribute("cartItemCount", this.GetCart().size());
				RequestDispatcher dispatcher = request.getRequestDispatcher(address);
				dispatcher.forward(request, response);					
			}
			else
			{
				address = "../login.jsp";
				response.sendRedirect(address);			
			}		
		} catch (ServletException e) { e.printStackTrace();
		} catch (IOException e) { e.printStackTrace();
		}			
	}	

	private boolean IsCustomerLoggedIn() 
	{
		boolean isLoggedIn = false;		
		if(session.getAttribute("customer")!= null) { isLoggedIn = true; }
		return isLoggedIn;
	}
	
	private BookBean GetSelectedBook(Integer bookId) 
	{
		HashMap<Integer, BookBean> bookList = (HashMap<Integer, BookBean>) session.getAttribute("bookList");		
		return bookList.get(bookId);
	}
	
	private void AddToCart(BookBean selectedBook) 
	{
		HashMap<Integer, BookBean> cart = this.GetCart();
		cart.put(selectedBook.getBookId(), selectedBook);
	}
	
	private HashMap<Integer, BookBean> GetCart()
	{
		if(session.getAttribute("cart") == null)
		{
			session.setAttribute("cart", new HashMap<Integer, BookBean>());
		}		
		return(HashMap<Integer, BookBean>)session.getAttribute("cart");	
	}
}
